package com.itheima.controller.backend.security;

/*import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户，如果用户不存在则抛出UsernameNotFoundException异常
        User user = Optional.ofNullable(userService.selectUserByUsername(username))
                .map(u -> {
                    // 获取用户的角色列表，并将其转换为String数组
                    String[] roles = userService.selectRolesByUserId(u.getId()).stream()
                            .map(Role::getKeyword)
                            .collect(Collectors.toList())
                            .toArray(new String[]{});
                    // 使用AuthorityUtils工具类创建GrantedAuthority列表
                    List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(roles);
                    // 设置用户的权限列表
                    u.setAuthorities(authorityList);
                    // 返回设置权限后的用户对象
                    return u;
                })
                // 如果用户不存在，则抛出UsernameNotFoundException异常
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        // 返回自定义的用户详情对象
        return new CustomUserDetails(user);
    }
}*/
